<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\Area;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户信息
 *
 * @icon fa fa-circle-o
 */
class Companion extends Backend
{

    /**
     * Companion模型对象
     * @var \app\admin\model\Companion
     */
    protected $model = null;
    protected $searchFields = 'name,phone';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Companion;
        $this->view->assign("roleList", $this->model->getRoleList());
        $this->view->assign("loginStatusList", $this->model->getLoginStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
 * 查看
 */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '', 'trim'), true);

            if (isset($filter['login_status'])) {
                $filter['login_status']=$filter['login_status']==1?'正常':'停用';
            }

            // 更新请求参数
            $this->request->get(['filter' => json_encode($filter, true)]);
            $this->request->get(['op' => json_encode($op, true)]);


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->where('companion.role','=','companion')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->login_status=$row->login_status=='正常'?'1':'0';
//                $provinceName = Area::where('id', $row['province'])->value('name');
//                $cityName = Area::where('id',$row['city'] )->value('name');
//                $districtName = Area::where('id', $row['district'])->value('name');
                $user_id=$row['user_id'];
                //$row->addr=$provinceName.$cityName.$districtName.$row->addr;
                $applicant='';
                if($user_id==null){
                    $applicant=\app\admin\model\Details::where('user_id','=',$row['applicant_id'])->find();
                }else{
                    if( $row['user']['agent_id']!=null){
                        $applicant=\app\admin\model\Details::where('user_id','=',$row['user']['agent_id'])->find();
                    }else if ($row['user']['room_id']!=null){
                        $applicant=\app\admin\model\Details::where('user_id','=',$row['user']['room_id'])->find();
                    }
                }
                 if($applicant){
                     $row->prole=$applicant['role']=='agent'?'代理'.'/'.$applicant['name']:"陪伴室".'/'.$applicant['name'];
                     $row->is_prole=1;
                 }else{
                     $row->prole='-';
                     $row->is_prole=0;
                 }

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 查看
     */
    public function online()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->where('companion.role','=','companion')
                ->whereNotNull('companion.user_id')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {


            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function fenpei($id,$pid){
        $user=\app\admin\model\User::where('id','=',$id)->find();
        $puser=\app\admin\model\User::where('id','=',$pid)->find();

        if($user['agent_id']!=null||$user['room_id']!=null){
            $this->error('该用户已经存在上级');
        }

        if($puser['role']=='room') {
            $result=\app\admin\model\User::where('id','=',$id)->update(['room_id'=>$pid]);
        }else if($puser['role']=='agent'){
            $result=\app\admin\model\User::where('id','=',$id)->update(['agent_id'=>$pid]);
        }else{
            $this->error('选择的用户不符合条件');
        }
        if($result>0){
            $this->success('操作成功');
        }
        $this->error('分配失败');
    }


    public function riderprice($id,$money){
        $details=\app\admin\model\Details::where('id','=',$id)->find();
        $result=\app\admin\model\Details::where('id','=',$id)->update(['price'=>$money]);
        if($result>0){
            $this->success('操作成功');
        }
        $this->error('修改失败');
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;

        }

        $result = false;
        Db::startTrans();
        try {
           $pd=  $this->model->where('user_id','=',$params['user_id'])->find();
           if($pd){
               $this->error(__('此账号已申请过'));
           }
            $area=\app\admin\model\Area::where('id','=',$params['city'])->find();
           $params['longitude']=$area['lng'];
            $params['latitude']=$area['lat'];
            User::where('id','=',$params['user_id'])->update(['role'=>'companion']);
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $area=\app\admin\model\Area::where('id','=',$params['city'])->find();
            $params['longitude']=$area['lng'];
            $params['latitude']=$area['lat'];

            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        foreach ($values as $item) {
            $values['login_status']=$item==1?'正常':'停用';
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
                $role=$values['login_status']=='正常'?'companion':'user';
                User::where('id','=',$item['user_id'])->update(['role'=>$role]);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

}
